//var sys = require('system');
//var pageUrl = ( sys.args[1] ) ? sys.args[1] : phantom.exit(0);
//
//function forceExit(){
//  phantom.exit(0);
//}
//
//var renderPage = function (url) {
//  var page = require('webpage').create();
//
//  page.onNavigationRequested = function(url, type, willNavigate, main) {
//      var tmpUrl = ( url.substr(url.length - 1) != '/' ) ? url+'/' : url;
//      var tmpPageUrl = ( pageUrl.substr( pageUrl.length - 1) != '/' ) ? pageUrl+'/' : pageUrl;
//      if (main && tmpUrl!=tmpPageUrl && url!='about:blank') {
//          pageUrl = url;
//          sys.stdout.write(url+'\n');
//          setTimeout(forceExit,1000 );
//      }
//  };
//
//  page.open(url, function(status) {
//      if ( status != 'success' ) {
//          phantom.exit( 1 );
//      } else {
//          phantom.exit( 0 );
//      }
//  },100);
//
//  setTimeout(forceExit,2000 );
//};
//
//renderPage( pageUrl );



"use strict";
var page = require('webpage').create(), system = require('system'), host, port, address, keyWords;
var keyWords = '';
if (system.args.length < 5) {
	console.log('Usage:  <proxyHost> <proxyPort> <URL>');
	phantom.exit(1);
} else {
	host = system.args[1];
	port = system.args[2];
	address = system.args[3];
	keyWords = system.args[4];
	if (host != 'ip' && port != '') {
		console.log('get data use proxy --');
		phantom.setProxy(host, port, 'manual', '', '');// 设置代理
	}
	console.log('get data begin --');
}
page.viewportSize = { width: 1920, height: 1080 };
page.settings.userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0';
//'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36';
//'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36';
page.settings.resourceTimeout = 30000; // 6 seconds
page.onResourceTimeout = function(e) {
    console.log(e.errorCode);   // it'll probably be 408
    console.log(e.errorString); // it'll probably be 'Network timeout on resource'
    console.log(e.url);         // the url whose request timed out
    phantom.exit(1);
};
page.onLoadFinished = function(status) {
	// console.log('get data --');
	// exitPhantom();
	//excuteClick(keyWords);
	
};

function openPage(root_url) {
	page.open(root_url, function(status) {
		if (status === "success") {
			console.log('page open is success :' + page.url+"--"+new Date());
			//window.setTimeout(function() {}, 4000);
			window.setTimeout(function(){excuteClick(keyWords);}, 15000);
		} else {
			console.log('page open is not success,phantomjs will exit!');
			// exitPhantom();
		}

	});
	window.setTimeout(function() {
		exitPhantom();
	}, 29000);
}

function closePage() {
	page.close();
}

function exitPhantom() {
	phantom.exit(1);
}

function excuteClick(keyWords) {
	var date = new Date();
	console.log('excuteClick --【' + keyWords + '】');
	try {
		var res = page.evaluate(function(kw) {
			var mouseClickEv;
			var hrefList = document.getElementsByClassName("r");
			var urlNew = hrefList.length;
			var temp = '';
			var str = '';
			var flag = "unFind";
			for ( var i = 0; i < hrefList.length; i++) {
				str = hrefList[i].innerHTML.replace(/\"/g,"");
				temp+=" ,"+i;
				if (kw != '' && str.indexOf(kw) != -1) {
					flag = "FTEXIST:"+str;
					mouseClickEv = document.createEvent("MouseEvents");
					mouseClickEv.initEvent("click", false, true);
					hrefList[i].getElementsByTagName("a")[0].dispatchEvent(mouseClickEv);
					break;
				} else {
					flag = "false";
				}
			}
			return flag+"--------"+temp;
		}, keyWords);
		
		console.log(' click result -->'+ res);
	} catch (e) {
		console.log('click error  --' + e.message);
	}

}

function goNextpage() {
	console.log('goNextpage - begin --');

	var res = page.evaluate(function() {
		var mouseClickEv;
		var nextPage = document.getElementById('pnnext');
		mouseClickEv = document.createEvent("MouseEvents");
		mouseClickEv.initEvent("click", false, true);
		nextPage.dispatchEvent(mouseClickEv);
		setTimeout(function() {
		}, 1000);
		setTimeout(function() {
			return "NEXTPAGEHREF:" + nextPage;
		}, 1000);
	});

	console.log('goNextpage -end --' + res);
}

openPage(address);

// setTimeout(exitPhantom(),1000000);
